package cn.virens.common.mybatis.dynamic_table.annotations.handler;

import cn.virens.common.mybatis.dynamic_table.DynamicTableNameFactory;
import cn.virens.common.mybatis.dynamic_table.annotations.VirDynamicTableNameContext;
import cn.virens.common.spring.annotations.VirAbstractMethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.dromara.hutool.core.collection.CollUtil;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

public class DynamicTableNameMethodInterceptor extends VirAbstractMethodInterceptor {
    protected final ExpressionParser parser = new SpelExpressionParser();

    @Override
    protected Object invoke(MethodInvocation invocation, AnnotationAttributes attributes) throws Throwable {
        VirDynamicTableNameContext context = new VirDynamicTableNameContext(invocation, attributes);

        CollUtil.forEach(context.variables(), (i, kv) -> {
            String k = CollUtil.get(kv, 0);
            String v = CollUtil.get(kv, 1);

            variable(context, k, v);
        });

        try {
            return invocation.proceed();
        } finally {
            this.clean(context);
        }
    }

    private void variable(VirDynamicTableNameContext context, String k, String v) {
        DynamicTableNameFactory.variable(k, () -> parse(context, v));
    }

    private String parse(VirDynamicTableNameContext context, String el) {
        return context.parse(parser, el, String.class);
    }

    private void clean(VirDynamicTableNameContext context) {
        if (context.clean()) {
            DynamicTableNameFactory.clean();
        }
    }
}
